/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.util.lang;

/**
 * @author Sven Schulz
 */
public class Longs {

	/*
	 * Taken from
	 * http://stackoverflow.com/questions/2632392/saturated-addition-of
	 * -two-signed-java-long-values
	 */
	public static long saturatedAdd(long x, long y) {
		// Sum ignoring overflow/underflow
		long s = x + y;

		// Long.MIN_VALUE if result positive (potential underflow)
		// Long.MAX_VALUE if result negative (potential overflow)
		long limit = Long.MIN_VALUE ^ (s >> 63);

		// -1 if overflow/underflow occurred, 0 otherwise
		long overflow = ((x ^ s) & ~(x ^ y)) >> 63;

		// limit if overflowed/underflowed, else s
		return ((limit ^ s) & overflow) ^ s;
	}
	
}